<template>
  <div class="integration-test" :class="{ 'dark': isDark }">
    <!-- 测试头部 -->
    <div class="test-header">
      <h1>智能体问答系统 - 集成测试</h1>
      <div class="test-controls">
        <el-button @click="runFullTest" :loading="isRunningTest" type="primary">
          完整测试
        </el-button>
        <el-button @click="runHealthCheck" :loading="isCheckingHealth">
          健康检查
        </el-button>
        <el-button @click="clearResults">清除结果</el-button>
      </div>
    </div>

    <!-- 系统状态面板 -->
    <div class="status-panel">
      <el-card>
        <template #header>
          <h3>系统状态</h3>
        </template>
        <div class="status-grid">
          <div class="status-item">
            <span class="label">API连接:</span>
            <el-tag :type="systemStatus.api.type">{{ systemStatus.api.text }}</el-tag>
          </div>
          <div class="status-item">
            <span class="label">SSE连接:</span>
            <el-tag :type="systemStatus.sse.type">{{ systemStatus.sse.text }}</el-tag>
          </div>
          <div class="status-item">
            <span class="label">会话数量:</span>
            <span>{{ chatStore.sessionCount }}</span>
          </div>
          <div class="status-item">
            <span class="label">MCP服务:</span>
            <span>{{ mcpStore.serviceCount.total }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 测试案例 -->
    <div class="test-cases">
      <el-card>
        <template #header>
          <h3>测试案例</h3>
        </template>
        <div class="test-case-list">
          <div
            v-for="testCase in testCases"
            :key="testCase.id"
            class="test-case"
            :class="getTestCaseClass(testCase)"
            @click="runSingleTest(testCase)"
          >
            <div class="test-case-header">
              <span class="test-name">{{ testCase.name }}</span>
              <div class="test-status">
                <el-icon v-if="testCase.status === 'running'">
                  <Loading />
                </el-icon>
                <el-icon v-else-if="testCase.status === 'passed'" class="success">
                  <Check />
                </el-icon>
                <el-icon v-else-if="testCase.status === 'failed'" class="error">
                  <Close />
                </el-icon>
                <el-icon v-else>
                  <Minus />
                </el-icon>
              </div>
            </div>
            <div class="test-description">{{ testCase.description }}</div>
            <div v-if="testCase.result" class="test-result">
              <div class="result-time">执行时间: {{ testCase.result.duration }}ms</div>
              <div v-if="testCase.result.error" class="result-error">
                错误: {{ testCase.result.error }}
              </div>
              <div v-if="testCase.result.details" class="result-details">
                <pre>{{ JSON.stringify(testCase.result.details, null, 2) }}</pre>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 实时日志 -->
    <div class="test-logs">
      <el-card>
        <template #header>
          <div class="logs-header">
            <h3>测试日志</h3>
            <el-button size="small" @click="clearLogs">清除日志</el-button>
          </div>
        </template>
        <div class="logs-content" ref="logsContainer">
          <div
            v-for="(log, index) in testLogs"
            :key="index"
            class="log-entry"
            :class="`log-${log.level}`"
          >
            <span class="log-time">{{ formatTime(log.timestamp) }}</span>
            <span class="log-level">{{ log.level.toUpperCase() }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 问答演示 -->
    <div class="chat-demo">
      <el-card>
        <template #header>
          <h3>问答演示</h3>
        </template>
        <div class="demo-controls">
          <el-input
            v-model="demoQuestion"
            placeholder="输入测试问题"
            style="margin-bottom: 12px"
          />
          <el-button 
            @click="sendDemoQuestion" 
            :loading="chatStore.isStreaming"
            type="primary"
          >
            发送问题
          </el-button>
          <el-button @click="clearDemoChat">清除对话</el-button>
        </div>
        <div class="demo-messages">
          <div
            v-for="message in currentMessages"
            :key="message.id"
            class="demo-message"
            :class="`message-${message.role}`"
          >
            <div class="message-header">
              <span class="message-role">{{ getRoleText(message.role) }}</span>
              <span class="message-time">{{ formatTime(message.timestamp) }}</span>
            </div>
            <div class="message-content">{{ message.content }}</div>
          </div>
          <div v-if="chatStore.isStreaming" class="demo-message message-assistant">
            <div class="message-header">
              <span class="message-role">AI助手</span>
              <span class="message-time">正在回复...</span>
            </div>
            <div class="message-content streaming-text">
              {{ chatStore.currentStreamingMessage }}
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { Loading, Check, Close, Minus } from '@element-plus/icons-vue'
import { useChatStore } from '@/stores/chat'
import { useTaskStore } from '@/stores/task'
import { useMCPStore } from '@/stores/mcp'
import { useUIStore } from '@/stores/ui'
import { healthCheck } from '@/init'
import { useSSE } from '@/services/sse'

// Stores
const chatStore = useChatStore()
const taskStore = useTaskStore()
const mcpStore = useMCPStore()
const uiStore = useUIStore()
const { isDark } = storeToRefs(uiStore)

// 响应式数据
const isRunningTest = ref(false)
const isCheckingHealth = ref(false)
const testLogs = ref<Array<{ timestamp: Date; level: string; message: string }>>([])
const logsContainer = ref<HTMLElement>()
const demoQuestion = ref('请帮我分析一下人工智能的发展趋势')

// 测试案例定义
interface TestCase {
  id: string
  name: string
  description: string
  status: 'pending' | 'running' | 'passed' | 'failed'
  result?: {
    duration: number
    error?: string
    details?: any
  }
  testFunction: () => Promise<void>
}

const testCases = ref<TestCase[]>([
  {
    id: 'health-check',
    name: '健康检查',
    description: '检查API连接、SSE连接和系统状态',
    status: 'pending',
    testFunction: testHealthCheck
  },
  {
    id: 'create-session',
    name: '创建会话',
    description: '测试创建新的聊天会话',
    status: 'pending',
    testFunction: testCreateSession
  },
  {
    id: 'send-message',
    name: '发送消息',
    description: '测试发送用户消息和接收回复',
    status: 'pending',
    testFunction: testSendMessage
  },
  {
    id: 'load-mcp-services',
    name: '加载MCP服务',
    description: '测试加载和管理MCP服务',
    status: 'pending',
    testFunction: testLoadMCPServices
  },
  {
    id: 'task-management',
    name: '任务管理',
    description: '测试任务创建、修改和执行',
    status: 'pending',
    testFunction: testTaskManagement
  },
  {
    id: 'sse-connection',
    name: 'SSE连接',
    description: '测试服务器推送事件连接',
    status: 'pending',
    testFunction: testSSEConnection
  }
])

// 计算属性
const systemStatus = computed(() => {
  const { getState } = useSSE()
  const sseState = getState()
  
  return {
    api: {
      type: 'success' as const,
      text: '已连接'
    },
    sse: {
      type: sseState === 'connected' ? 'success' : 'warning' as const,
      text: sseState === 'connected' ? '已连接' : '未连接'
    }
  }
})

const currentMessages = computed(() => chatStore.currentMessages)

// 方法
const log = (level: string, message: string) => {
  testLogs.value.push({
    timestamp: new Date(),
    level,
    message
  })
  
  nextTick(() => {
    if (logsContainer.value) {
      logsContainer.value.scrollTop = logsContainer.value.scrollHeight
    }
  })
}

const getTestCaseClass = (testCase: TestCase) => {
  return {
    'test-pending': testCase.status === 'pending',
    'test-running': testCase.status === 'running',
    'test-passed': testCase.status === 'passed',
    'test-failed': testCase.status === 'failed'
  }
}

const formatTime = (timestamp: Date | string) => {
  const date = typeof timestamp === 'string' ? new Date(timestamp) : timestamp
  return date.toLocaleTimeString('zh-CN')
}

const getRoleText = (role: string) => {
  const roleMap = {
    user: '用户',
    assistant: 'AI助手',
    system: '系统'
  }
  return roleMap[role] || role
}

// 测试函数
async function testHealthCheck(): Promise<void> {
  log('info', '开始健康检查...')
  const health = await healthCheck()
  
  if (health.status === 'healthy') {
    log('success', '健康检查通过')
  } else {
    log('error', '健康检查失败')
    throw new Error(`健康检查失败: ${JSON.stringify(health.details)}`)
  }
}

async function testCreateSession(): Promise<void> {
  log('info', '创建新会话...')
  const sessionId = await chatStore.createSession()
  chatStore.setCurrentSession(sessionId)
  log('success', `会话创建成功: ${sessionId}`)
}

async function testSendMessage(): Promise<void> {
  log('info', '发送测试消息...')
  
  if (!chatStore.hasCurrentSession) {
    await testCreateSession()
  }
  
  try {
    await chatStore.sendMessage('Hello, this is a test message.')
    log('success', '消息发送成功')
  } catch (error) {
    log('error', `消息发送失败: ${error}`)
    throw error
  }
}

async function testLoadMCPServices(): Promise<void> {
  log('info', '加载MCP服务...')
  try {
    await mcpStore.loadServices()
    log('success', `MCP服务加载成功，共 ${mcpStore.serviceCount.total} 个服务`)
  } catch (error) {
    log('warning', `MCP服务加载失败: ${error}`)
    // MCP服务加载失败不应该阻止其他测试
  }
}

async function testTaskManagement(): Promise<void> {
  log('info', '测试任务管理...')
  
  // 创建测试任务
  const task = taskStore.addTask({
    sessionId: chatStore.currentSessionId || 'test-session',
    description: '测试任务',
    type: 'ANALYSIS',
    status: 'PENDING',
    priority: 1,
    sequence: 1,
    dependencies: [],
    agentType: 'GENERAL_QA',
    estimatedTime: 30,
    progress: 0
  })
  
  log('success', `任务创建成功: ${task.id}`)
  
  // 更新任务状态
  taskStore.updateTask(task.id, { status: 'COMPLETED', progress: 100 })
  log('success', '任务状态更新成功')
}

async function testSSEConnection(): Promise<void> {
  log('info', '测试SSE连接...')
  const { getState } = useSSE()
  const state = getState()
  
  if (state === 'connected') {
    log('success', 'SSE连接正常')
  } else {
    log('warning', `SSE连接状态: ${state}`)
  }
}

// 事件处理
const runSingleTest = async (testCase: TestCase) => {
  if (testCase.status === 'running') return
  
  const startTime = Date.now()
  testCase.status = 'running'
  testCase.result = undefined
  
  try {
    await testCase.testFunction()
    testCase.status = 'passed'
    testCase.result = {
      duration: Date.now() - startTime
    }
    log('success', `测试通过: ${testCase.name}`)
  } catch (error) {
    testCase.status = 'failed'
    testCase.result = {
      duration: Date.now() - startTime,
      error: (error as Error).message
    }
    log('error', `测试失败: ${testCase.name} - ${(error as Error).message}`)
  }
}

const runFullTest = async () => {
  if (isRunningTest.value) return
  
  isRunningTest.value = true
  log('info', '开始完整测试...')
  
  let passedCount = 0
  let totalCount = testCases.value.length
  
  for (const testCase of testCases.value) {
    await runSingleTest(testCase)
    if (testCase.status === 'passed') {
      passedCount++
    }
  }
  
  isRunningTest.value = false
  
  const message = `测试完成: ${passedCount}/${totalCount} 通过`
  log('info', message)
  
  if (passedCount === totalCount) {
    ElMessage.success(message)
  } else {
    ElMessage.warning(message)
  }
}

const runHealthCheck = async () => {
  if (isCheckingHealth.value) return
  
  isCheckingHealth.value = true
  
  try {
    const health = await healthCheck()
    log('info', `健康检查结果: ${health.status}`)
    log('info', JSON.stringify(health.details, null, 2))
    
    if (health.status === 'healthy') {
      ElMessage.success('系统健康状态良好')
    } else {
      ElMessage.warning('系统健康状态异常')
    }
  } catch (error) {
    log('error', `健康检查失败: ${error}`)
    ElMessage.error('健康检查失败')
  } finally {
    isCheckingHealth.value = false
  }
}

const clearResults = () => {
  testCases.value.forEach(testCase => {
    testCase.status = 'pending'
    testCase.result = undefined
  })
  log('info', '测试结果已清除')
}

const clearLogs = () => {
  testLogs.value = []
}

const sendDemoQuestion = async () => {
  if (!demoQuestion.value.trim()) return
  
  try {
    if (!chatStore.hasCurrentSession) {
      const sessionId = await chatStore.createSession()
      chatStore.setCurrentSession(sessionId)
    }
    
    await chatStore.sendMessage(demoQuestion.value)
    demoQuestion.value = ''
  } catch (error) {
    ElMessage.error('发送问题失败')
    log('error', `发送问题失败: ${error}`)
  }
}

const clearDemoChat = () => {
  chatStore.clearMessages()
}

// 初始化
onMounted(() => {
  log('info', '集成测试页面已加载')
})
</script>

<style scoped lang="scss">
.integration-test {
  padding: 24px;
  min-height: 100vh;
  background: var(--el-bg-color-page);
  
  .test-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    h1 {
      margin: 0;
      color: var(--el-text-color-primary);
    }
    
    .test-controls {
      display: flex;
      gap: 12px;
    }
  }
  
  .status-panel {
    margin-bottom: 24px;
    
    .status-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;
      
      .status-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .label {
          font-weight: 500;
          color: var(--el-text-color-regular);
        }
      }
    }
  }
  
  .test-cases {
    margin-bottom: 24px;
    
    .test-case-list {
      display: grid;
      gap: 12px;
      
      .test-case {
        padding: 16px;
        border: 1px solid var(--el-border-color);
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s ease;
        
        &:hover {
          border-color: var(--el-color-primary);
        }
        
        &.test-running {
          border-color: var(--el-color-primary);
          background: var(--el-color-primary-light-9);
        }
        
        &.test-passed {
          border-color: var(--el-color-success);
          background: var(--el-color-success-light-9);
        }
        
        &.test-failed {
          border-color: var(--el-color-danger);
          background: var(--el-color-danger-light-9);
        }
        
        .test-case-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          
          .test-name {
            font-weight: 600;
            color: var(--el-text-color-primary);
          }
          
          .success {
            color: var(--el-color-success);
          }
          
          .error {
            color: var(--el-color-danger);
          }
        }
        
        .test-description {
          color: var(--el-text-color-regular);
          margin-bottom: 8px;
        }
        
        .test-result {
          margin-top: 12px;
          padding-top: 12px;
          border-top: 1px solid var(--el-border-color-lighter);
          font-size: 12px;
          
          .result-time {
            color: var(--el-text-color-secondary);
          }
          
          .result-error {
            color: var(--el-color-danger);
            margin-top: 4px;
          }
          
          .result-details {
            margin-top: 8px;
            
            pre {
              background: var(--el-bg-color-page);
              padding: 8px;
              border-radius: 4px;
              font-size: 11px;
              overflow-x: auto;
            }
          }
        }
      }
    }
  }
  
  .test-logs {
    margin-bottom: 24px;
    
    .logs-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h3 {
        margin: 0;
      }
    }
    
    .logs-content {
      max-height: 300px;
      overflow-y: auto;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 12px;
      
      .log-entry {
        display: flex;
        gap: 8px;
        padding: 4px 0;
        border-bottom: 1px solid var(--el-border-color-lighter);
        
        .log-time {
          flex-shrink: 0;
          color: var(--el-text-color-placeholder);
        }
        
        .log-level {
          flex-shrink: 0;
          font-weight: 600;
          min-width: 60px;
        }
        
        .log-message {
          flex: 1;
          color: var(--el-text-color-primary);
        }
        
        &.log-success .log-level {
          color: var(--el-color-success);
        }
        
        &.log-error .log-level {
          color: var(--el-color-danger);
        }
        
        &.log-warning .log-level {
          color: var(--el-color-warning);
        }
        
        &.log-info .log-level {
          color: var(--el-color-primary);
        }
      }
    }
  }
  
  .chat-demo {
    .demo-controls {
      margin-bottom: 16px;
    }
    
    .demo-messages {
      max-height: 400px;
      overflow-y: auto;
      
      .demo-message {
        margin-bottom: 16px;
        padding: 12px;
        border-radius: 8px;
        
        &.message-user {
          background: var(--el-color-primary-light-9);
          margin-left: 20%;
        }
        
        &.message-assistant {
          background: var(--el-bg-color-overlay);
          margin-right: 20%;
        }
        
        .message-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          font-size: 12px;
          
          .message-role {
            font-weight: 600;
            color: var(--el-text-color-primary);
          }
          
          .message-time {
            color: var(--el-text-color-placeholder);
          }
        }
        
        .message-content {
          color: var(--el-text-color-primary);
          line-height: 1.5;
          
          &.streaming-text::after {
            content: '●';
            animation: pulse 1s infinite;
            margin-left: 4px;
          }
        }
      }
    }
  }
}
</style>